<?php

namespace app\tenant\controller;

use app\common\constant\Platform;
use app\common\model\MediaImage;
use app\common\model\MediaFile;
use app\common\model\MediaText;
use app\common\model\MediaVideo;
use app\common\model\MediaLink;
use app\common\model\TenantApp as TenantAppM;
use app\common\service\MediaGroup as GroupService;
use app\common\service\Tenant as TenantService;
use app\common\service\Upload;
use app\common\service\Media as MediaService;
use app\TenantController;
use support\View;
use think\facade\Db;
use Support\Request;;

class Media extends TenantController
{
    /**
     * @var MediaLink
     */
    private $linkM;
    /**
     * @var MediaImage
     */
    private $imageM;
    /**
     * @var MediaText
     */
    private $textM;
    /**
     * @var MediaFile
     */
    private $fileM;
    /**
     * @var MediaVideo
     */
    private $videoM;

    private $types = [
        'text','image', 'video', 'file', 'link'
    ];

    /**
     * 控制器/类名
     * @var string
     */
    public $controller = null;
    /**
     * @var Upload
     */
    private Upload $uploadService;

    public function __construct()
    {
        parent::__construct(); // TODO: Change the autogenerated stub
        set_time_limit(0);
        $this->imageM = new MediaImage();
        $this->textM = new MediaText();
        $this->fileM = new MediaFile();
        $this->videoM = new MediaVideo();
        $this->linkM = new MediaLink();
        View::assign('config', dao_config('system.upload'));
        $this->uploadService = new Upload(dao_config('system.upload'));
        $this->types = array_keys(MediaService::types());
    }

    private function getPrefix(){
        return 'tenant_'.$this->tenantInfo('id');
    }

    /**
     * 素材上传
     * Author: fudaoji<fdj@kuryun.cn>
     */
    public function uploadPost(){
        if(request()->isPost()) {
            $post_data = input('');
            $res = $this->uploadService->upload(request()->file(), Upload::config($post_data['type']), ['uid' => $this->getPrefix()]);

            if($res['code']){
                foreach ($res['data'] as $item){
                    $insert_data = [
                        'company_id' => TenantService::getCompanyId(),
                        'title' => $item['original_name'],
                        'url' => $item['url'],
                        'size' => $item['size'],
                        'ext' => $item['ext']
                    ];
                    $this->getModel($post_data['type'])->create($insert_data);
                }
                return $this->success('上传成功');
            }else{
                return $this->error($res['msg']);
            }
        }
    }

    private function getModel($type = 'image'){
        $list = [
            MediaService::IMAGE => $this->imageM,
            MediaService::TEXT => $this->textM,
            MediaService::FILE => $this->fileM,
            MediaService::VIDEO => $this->videoM,
            MediaService::LINK => $this->linkM,
        ];
        return isset($list[$type]) ? $list[$type] : null;
    }

    /**
     * 选择app
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * Author: fudaoji<fdj@kuryun.cn>
     */
    public function app(){
        $field = input('field', ''); //目标input框
        $search_key = input('search_key', '');
        $where = [
            $this->tenantWhere('ta'),
            ['app.status','=', 1],
            ['ta.deadline','>', time()],
            ['type','like', '%'.Platform::MINI.'%']
        ];
        $search_key && $where[] = ['title', 'like', '%'.$search_key.'%'];
        $data_list = TenantAppM::alias('ta')
            ->where($where)
            ->join('app app', 'app.name=ta.app_name')
            ->field(['app.*', 'ta.deadline'])
            ->order(['ta.id' => 'desc'])
            ->paginate(7);

        $pager = $data_list->render();
        $assign = ['data_list' => $data_list, 'pager' => $pager, 'field' => $field];
        return $this->show($assign);
    }

    /**
     * 弹框素材列表
     * @param Request $request
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * Author: fudaoji<fdj@kuryun.cn>
     */
    public function choose(Request $request){
        $type = input('type', MediaService::IMAGE);
        $search_key = input('search_key', '');
        $where = [
            $this->tenantWhere()
        ];
        $search_key && $where[] = ['title', 'like', '%'.$search_key.'%'];
        $group_id = input('group_id', -1);
        $group_id >= 0 && $where[] = ['group_id', '=', $group_id];

        $query = $this->getModel($type)->where($where);
        $data_list = $query->order('id', 'desc')
            ->paginate(12);

        $pager = $data_list->appends(['type' => $type, 'search_key' => $search_key])->render();
        $assign = [
            'group_id' => $group_id,
            'groups' => [0=>'未分组'] + GroupService::getIdToTitle(),
            'data_list' => $data_list,
            'type' => $type,
            'pager' => $pager,
            'config' => dao_config('system.upload'),
            'field' => input('field', '') //目标input框
        ];
        return $this->show($assign);
    }

    /**
     * 删除素材
     * Author: fudaoji<fdj@kuryun.cn>
     */
    public function delPost(){
        $post_data = input();
        $ids = $post_data['ids'];
        $model = $this->getModel($post_data['type']);
        Db::startTrans();
        try {
            foreach ($ids as $id){
                $data = $model->where([$this->tenantWhere()])->find($id);
                if($model->where([$this->tenantWhere(), ['id', '=', $id]])->delete()){
                    !empty($data['location']) && strtolower($data['location']) == 'local' && @unlink($data['path']); //删除本地文件
                }
            }
            Db::commit();
            return $this->success('操作成功!');
        }catch (\Exception $e){
            dao_log()->error(json_encode($e->getMessage()));
            Db::rollback();
            return $this->error('系统错误，请刷新重试!');
        }
    }

    /**
     * 设置分组
     * Author: fudaoji<fdj@kuryun.cn>
     */
    public function setGroupPost(){
        $post_data = input();
        $ids = $post_data['ids'];
        $model = $this->getModel($post_data['type']);
        Db::startTrans();
        try {
            $where = [
                $this->tenantWhere(),
                ['id', 'in', $ids]
            ];
            $model->where($where)->update(['group_id' => $post_data['group_id']]);
            Db::commit();
            return $this->success('操作成功!');
        }catch (\Exception $e){
            dao_log()->error($e->getMessage());
            Db::rollback();
            return $this->error('系统错误，请刷新重试或联系管理员');
        }
    }
}